package com.yyds.blackmagic.interceptor;

import com.google.gson.Gson;
import com.yyds.blackmagic.Annotation.JwtAnno;
import com.yyds.blackmagic.utils.JwtUtils;
import com.yyds.blackmagic.vo.ActionResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;

/**
 * @Author ccc
 * @Date 2021/12/13
 * @Descripton
 */
@Component  //实现Bean的注入
@Slf4j
public class JwtInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String token = request.getHeader("token");
        String requestURI = request.getRequestURI();
        log.info("path:"+requestURI);
        //拦截处理器方法
        if(handler instanceof HandlerMethod){
            //获取处理器方法上的注解
            HandlerMethod method = (HandlerMethod) handler;
            JwtAnno jwtAnno = method.getMethodAnnotation(JwtAnno.class);
            if(jwtAnno!=null){
                //如果有@JwtAnno注解，必须进行JWT令牌校验合法后访问
                if(!StringUtils.isEmpty(token)){
                    log.info("token:"+token);
                    boolean b = JwtUtils.verifyToken(token);
                    if(b){
                        return true;
                    }else {  //如果令牌不合法，拒绝继续访问
                        response.setContentType("application/json;charset=UTF-8");
                        log.info("非法令牌："+token);
                        PrintWriter out = response.getWriter();
                        ActionResult result = new ActionResult(HttpStatus.UNAUTHORIZED.value(), "unauth", null);
                        String json = new Gson().toJson(result);
                        out.write(json);
                        out.flush();
                        out.close();
                        log.info("非法令牌2："+token);
                        return false;
                    }
                }else { //如果令牌为空，拒绝继续访问
                    response.setContentType("application/json;charset=UTF-8");
                    PrintWriter out = response.getWriter();
                    ActionResult result = new ActionResult(HttpStatus.UNAUTHORIZED.value(), "unauth", null);
                    String json = new Gson().toJson(result);
                    out.write(json);
                    out.flush();
                    out.close();
                    return false;
                }
            }else {
                log.info("running...");
                return true;
            }
        }
        return true;
    }
}
